<?php
namespace app\api\controller\v1;
use app\api\logic\GetAddressLogic;
use think\Db;
use app\service\TechnService;
class Service extends Base
{
	public function _initialize()
	{
		parent::_initialize();
	}

	/**
	 * 服务列表
	 */
	public function lists()
	{
		$params = $this->data_post;
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$map = [
			'is_shelves' => 1,
			'is_delete_time' => 0
		];
		if(!empty($params['class_id'])){
		    $map['class_id']=$params['class_id'];
		}else{
            $map['class_id']=0;
        }
		$list_data = Db::name('service')->where($map)->order('sort asc')->select();
		if(!empty($list_data))
		{
			//遍历处理
			foreach($list_data as $key => $value)
			{
				//图片
				$list_data[$key]['images'] = request()->domain().$value['images'];

				//价格美化
				$list_data[$key]['price'] = PriceBeautify($value['price']);
				$list_data[$key]['original_price'] = PriceBeautify($value['original_price']);
			}
			$result['code'] = 0;
	        $result['msg'] = "请求成功";
	        $result['data'] = $list_data;
	        
	        
	        $result['service_class']=db::name('service_class')->where('is_delete_time',0)->select();
		}else
		{
			$result['code'] = -1;
	        $result['msg'] = "暂无数据";
		}
		echo json_encode($result);
	}

	/**
	 * 服务详情
	 */
	public function detail()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		//dump($params);
		$validate = $this->validate(
			$params,
			[
				'service_id' => 'require'
			],
			[
				'service_id.require' => '服务id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //查询服务信息
        $info = Db::name('service')->where(['id' => $params['service_id'], 'is_shelves' => 1, 'is_delete_time' => 0])->find();
        if(empty($info))
        {
        	echo json_encode(['code' => -1, 'msg' => '服务不存在']);
            exit();
        }
        //处理轮播图片
        $carousels_array = [];
        if(!empty($info['carousels']))
        {
        	$carousels_array = explode(",", $info['carousels']);
        	foreach($carousels_array as $key => $value)
        	{
        		$carousels_array[$key] = request()->domain().$value;
        	}
        }
        $info['carousels_array'] = $carousels_array;

        //服务详情
        $info['introduce'] = ApMiniRichTextContentHandle(ContentStaticReplace($info['introduce'],'get'));
        $info['taboos'] = ApMiniRichTextContentHandle(ContentStaticReplace($info['taboos'],'get'));
        $info['notice'] = ApMiniRichTextContentHandle(ContentStaticReplace($info['notice'],'get'));

        $result['code'] = 0;
	    $result['msg'] = "请求成功";
	    $result['data'] = $info;
        echo json_encode($result);
	}

	/**
	 * 服务预约时间
	 */
	public function pre_time()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
        
        //dump($params);
        //当前时间
        $current_time = time();
        //预约间隔时间(15分钟)
        $interval_time = $current_time+900;
        //最终预约时间
        $final_time = $interval_time;
        //技师预约时间节点
        $reservation_node = [];
        //如果技师id存在查询技师
        $techn_info = [];
        if(!empty($params['techn_id']))
        {
        	$techn_info = Db::name('techn')->where(['id' => $params['techn_id']])->find();
        	if(!empty($techn_info))
        	{
        		$techn_info['no_pre_hour_slot'] = !empty($techn_info['no_pre_hour_slot']) ? json_decode($techn_info['no_pre_hour_slot'], true) : [];
        		//查询技师已预约的订单
        		$order_list = Db::name('order')->where(['techn_id' => $techn_info['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0])->select();
        		if(!empty($order_list))
        		{
        			foreach($order_list as $key => $value)
        			{
        				if(!empty($value['pre_start_time']) && !empty($value['pre_end_time']))
        				{
        					//处理时间节点
        					/*if($value['service_time'] > 0)
        					{
        						//如果开始服务
        					    $pre_start_time = $value['service_time'];
        					    $pre_end_time = $value['service_time']+($value['buy_number_duration']*60)+900;
        					}else
        					{*/
        						$pre_start_time = $value['pre_start_time'];
        					    $pre_end_time = $value['pre_end_time']+900;
        					/*}*/
        					for($j = $pre_start_time; $j <= $pre_end_time; $j += 1800)
        					{
        						$reservation_node[] = date('Y-m-d H:i:s', $j);
        					}
        				}
        			}
        		}
        	}
        }
        //dump($techn_info);
		$list_data = [];
		$week_arr = ["周日","周一","周二","周三","周四","周五","周六"];
		//开始时间
		$start_time = strtotime(date('Y-m-d', time()));
		//结束时间
		$end_time = strtotime(date('Y-m-d', strtotime("+2 day")));
		//算出开始时间与结束时间中间间隔的时间
		$key = 0;
		for($i = $start_time; $i <= $end_time; $i += 86400)
		{
			$list_data[$key]['day'] = date('m-d', $i);
			$list_data[$key]['week'] = $week_arr[date("w", $i)];

			$time_slot = [];
			$slot_key = 0;
			//如果技师接单状态
			if(!empty($techn_info) && $techn_info['work_status'] == 1)
			{
				//开始时间段
				$start_slot = strtotime(date('Y-m-d', $i).' 00:00:00');
				//结束时间段
				$end_slot = strtotime(date('Y-m-d', $i).' 23:59:59');
				//判断是否选择接单开始时间与结束时间
				$work_start_hour = !empty($techn_info['work_start_hour']) ? strtotime(date('Y-m-d', $i).' '.$techn_info['work_start_hour'].':00') : strtotime(date('Y-m-d', $i).' 00:00:00');
				
				$work_end_hour = !empty($techn_info['work_end_hour']) ? strtotime(date('Y-m-d', $i).' '.$techn_info['work_end_hour'].':00') : strtotime(date('Y-m-d', $i).' 23:59:59');
				for($j = $start_slot; $j <= $end_slot; $j += 1800)
				{
					//如果大于当前时间才显示
					if($work_start_hour > $work_end_hour)
					{
						if($j >= $final_time && ($j >= $work_start_hour || $j <= $work_end_hour) && !in_array(date('Y-m-d H:i:s', $j), $techn_info['no_pre_hour_slot']) && !in_array(date('Y-m-d H:i:s', $j), $reservation_node))
						{
							$time_slot[$slot_key]['time'] = date('H:i', $j);
							$time_slot[$slot_key]['date'] = date('Y-m-d H:i:s', $j);
							$slot_key++;
						}
					}elseif ($work_start_hour < $work_end_hour) {
						if($j >= $final_time && $j >= $work_start_hour && $j <= $work_end_hour && !in_array(date('Y-m-d H:i:s', $j), $techn_info['no_pre_hour_slot']) && !in_array(date('Y-m-d H:i:s', $j), $reservation_node))
						{
							$time_slot[$slot_key]['time'] = date('H:i', $j);
							$time_slot[$slot_key]['date'] = date('Y-m-d H:i:s', $j);
							$slot_key++;
						}
					}else
					{
						if($j >= $final_time && !in_array(date('Y-m-d H:i:s', $j), $techn_info['no_pre_hour_slot']) && !in_array(date('Y-m-d H:i:s', $j), $reservation_node))
						{
							$time_slot[$slot_key]['time'] = date('H:i', $j);
							$time_slot[$slot_key]['date'] = date('Y-m-d H:i:s', $j);
							$slot_key++;
						}
					}
				}
			}
			$list_data[$key]['time_slot'] = $time_slot;
			$key++;
		}
		$result['code'] = 0;
	    $result['msg'] = "请求成功";
	    $result['data'] = $list_data;
	    echo json_encode($result);
	}

	/**
	 * 获取当前服务下的技师
	 */
	public function techn_lis()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
// 		$user = $this->user;
		
		//dump($params);
		//表单验证
		$validate = $this->validate(
			$params,
			[
				'service_id' => 'require',
				'lng' => 'require',
				'lat' => 'require',
				'page' => 'require'
			],
			[
				'service_id.require' => '服务信息有误',
				'lng.require' => '坐标信息有误',
				'lat.require' => '坐标信息有误',
				'page.require' => '分页有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        $lat = $params['lat']; //latitude
        $lon = $params['lng']; //longitude
        $distance = 50; //your distance in KM
        $R = 6371; //constant earth radius. You can add precision here if you wish
        $maxLat = $lat + rad2deg($distance/$R);
		$minLat = $lat - rad2deg($distance/$R);
		$maxLon = $lon + rad2deg(asin($distance/$R) / cos(deg2rad($lat)));
		$minLon = $lon - rad2deg(asin($distance/$R) / cos(deg2rad($lat)));

	    $map = [
	    	'T.service_ids' => ['like', '%,'.$params['service_id'].',%'],
	    	'TL.lat' => [['EGT', $minLat], ['ELT', $maxLat]],
	    	'TL.lng' => [['EGT', $minLon], ['ELT', $maxLon]],
	    	'T.work_status' => ['in', '1,2']
	    ];




        if(!empty($params['nickname']))
		{
			$map['T.nickname'] = ['like','%'.$params['nickname'].'%'];
		}


        $citycode = GetAddressLogic::change_address($lon,$lat);
        if ($citycode){
            $city = Db::name('area')->where('city_code',$citycode)->where('lev',2)->find();
            $map['T.city'] = $city['id'];
        }
        $params['city'] = $city['id'];
        $citycode = GetAddressLogic::change_address_qu($lon,$lat);

        //        如果该城市有县级列表,去掉该市的县
        $is_city = Db::name('proxy')->where('qu',$citycode)->find();

        if(!empty($is_city)){
            if ($is_city['is_xian'] == 1){
//                $map = [
//                    'T.county'=>$citycode,
//                    'T.work_status' => ['in', '1,2'],
//                ];
                $map['T.county'] = $citycode;
                $map['T.work_status'] = ['in', '1,2'];
            }else{
//                $map = [
//                    'T.city'=>$is_city['shi'],
//                    'T.work_status' => ['in', '1,2'],
//                ];

                $map['T.city'] = $is_city['shi'];
                $map['T.work_status'] = ['in', '1,2'];
            }
        }else{
            $cityid = Db::name('proxy')->where('shi',$city['id'])->where('is_xian',1)->column('proxy_id');
            $city_id = Db::name('proxy')->where('shi',$city['id'])->where('is_xian',0)->find();

            if (empty($cityid)){


//                $map = [
//                    'T.city'=>$city['id'],
//                    'T.work_status' => ['in', '1,2'],
//                ];

                $map['T.city'] = $city['id'];
                $map['T.work_status'] = ['in', '1,2'];
            }else{

                $not = implode(',',$cityid);

//                $map = [
//                    'T.city' => $city['id'],
//                    'T.county' => ['not in',$not],
//                    'T.work_status' => ['in', '1,2']
//                ];

                $map['T.city'] = $city['id'];
                $map['T.county'] = ['not in',$not];
                $map['T.work_status'] = ['in', '1,2'];

            }

        }
// 		$map['work_status']=1;
		$field_lat = 'TL.lat';
		$field_lng = 'TL.lng';
		$lat = $params['lat'];
		$lng = $params['lng'];
		$list_data = Db::name('techn')
		             ->alias('T')
		             ->join('__TECHN_LAST__ TL', 'T.id = TL.techn_id', 'LEFT')
		             ->field("T.*, (6378.138 * 2 * asin(sqrt(pow(sin(({$field_lat} * pi() / 180 - {$lat} * pi() / 180) / 2),2) + cos({$field_lat} * pi() / 180) * cos({$lat} * pi() / 180) * pow(sin(({$field_lng} * pi() / 180 - {$lng} * pi() / 180) / 2),2))) * 1000) as distance")
		             ->where($map)
		             ->order('work_status asc,pre_time_y asc, distance asc')
		             ->limit(($params['page']-1)*10,10)
		             ->select();
		if(!empty($list_data))
		{
			//遍历处理
			foreach($list_data as $key => $value)
			{
				//处理工作形象照片
				$list_data[$key]['work_img'] = request()->domain().$value['work_img'];
				//处理个人生活照片
		        $self_img_array = explode(",", $value['self_img']);
		        foreach($self_img_array as $si_key => $si_value)
		        {
		        	$self_img_array[$si_key] = request()->domain().$si_value;
		        }
		        $list_data[$key]['self_img_array'] = $self_img_array;
				//处理技师工作状态
				$new_work_status = 0;
				$new_work_status_name = '';
				// if($value['work_status'] == 1)
				// {
				// 	//查询技师是否有下在进行中的订单
				// 	$run_order_info = Db::name('order')->where(['techn_id' => $value['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0])->find();
				// 	if(empty($run_order_info))
				// 	{
				// 		$new_work_status = 1;
				// 		$new_work_status_name = '可服务';
				// 	}else
				// 	{
				// 		$new_work_status = 2;
				// 		$new_work_status_name = '可预约';
				// 	}
				// }elseif($value['work_status'] == 2)
				// {
				// 	$new_work_status = 3;
				// 	$new_work_status_name = '休息中';
				// }
				
				if(!empty($value['pre_time_y'])){
    				if($value['pre_time_y']-time()>2700){
    				    $new_work_status = 2;
    					$new_work_status_name = '可预约';
    				}else{
    				    $new_work_status = 1;
    					$new_work_status_name = '可服务';
    				}
				}else{
				    $new_work_status = 3;
					$new_work_status_name = '休息中';
				}
				
				$list_data[$key]['new_work_status'] = $new_work_status;
				$list_data[$key]['new_work_status_name'] = $new_work_status_name;
				//距离
				$int_distance = PriceNumberFormat($value['distance']/1000);
				$list_data[$key]['distance'] = $int_distance.'km';
				//技师最早可预约时间
				// $pre_time = '';
				// $techn_pre_time = TechnService::TechnPreTime(['techn_id' => $value['id']]);
				// if(!empty($techn_pre_time))
				// {
				// 	$pre_time_array = array_merge_recursive($techn_pre_time[0]['time_slot'], $techn_pre_time[1]['time_slot'], $techn_pre_time[2]['time_slot']);
				// 	if(!empty($pre_time_array))
				// 	{
				// 		$pre_time = $pre_time_array[0]['time'];
				// 	}
				// }
				$daymsg='后天 ';
				
				if(!empty($value['pre_time_y'])){
				    if(date('d',$value['pre_time_y'])==date('d')){
    				    $daymsg='今天 ';
    				}else if(date('d',$value['pre_time_y'])==date('d',time()+86400)){
    				    $daymsg='明天 ';
    				}
				    $list_data[$key]['pre_time'] =$daymsg. date('H:i',$value['pre_time_y']);
				}else{
				    $list_data[$key]['pre_time'] = '';
				}
                //获取技师等级图标 收藏数  评论数
                $level = Db::name('techn_last')->where('techn_id',$value['id'])->find();
                $level_info = Db::name('techn_level')->where('id',$level['level_id'])->find();
                if (!empty($level_info))
                    $level_url = '/static/'.$level_info['rank'].'x.png';
                else
                    $level_url = '';

                $list_data[$key]['level_url'] = $level_url;

                //                是新人
                if (time() - $value['add_time'] < 259200){
                    $list_data[$key]['is_new'] = 1;
                }else{
                    $list_data[$key]['is_new'] = 0;
                }
                //是销冠
                $guan = Db::name('techn_last')->order('total_result desc')->where('city',$params['city'])->where('techn_id','<>','299')->limit(0,3)->column('techn_id');
                if (!empty($guan) && in_array($value['id'],$guan)){
                    $list_data[$key]['is_guan'] = 1;
                }else{
                    $list_data[$key]['is_guan'] = 0;
                }
                //是热门
                $hot = Db::name('techn_last')->order('total_result desc')->where('city',$params['city'])->where('techn_id','<>','299')->limit(4,5)->column('techn_id');
                if (!empty($hot) && in_array($value['id'],$hot)){
                    $list_data[$key]['is_hot'] = 1;
                }else{
                    $list_data[$key]['is_hot'] = 0;
                }
                $talk_num = Db::name('talk')->where('techn_id',$value['id'])->count('id');
                $all_xing = Db::name('talk')->where('techn_id',$value['id'])->sum('service_level');
                if (!empty($all_xing) && !empty($talk_num)){
                    $xing = round($all_xing/$talk_num,1);
                }else{
                    $xing = '4.'.rand(5,9);
                }
                $list_data[$key]['xing'] = $xing;
                $list_data[$key]['talk_num'] = Db::name('talk')->where('techn_id',$value['id'])->column('count(id)')[0];
                //评价列表
                $talk_list = Db::name('talk')->where('techn_id',$value['id'])->order('add_time desc')->select();
                $talk_titles = Db::name('talk_title')->where('is_delete_time',0)->column('talk_title','id');
                if (!empty($talk_list)){
                    foreach ($talk_list as $kk => $vv){
                        $talk_list[$kk]['add_time'] = date('m-d',$vv['add_time']);
                        $vv['title_ids'] = json_decode($vv['title_ids']);
                        foreach ($vv['title_ids'] as $vvv){
                            $talk_list[$kk]['titles'][] = $talk_titles[$vvv];
                        }

                    }
                }
                $list_data[$key]['talk_list'] = $talk_list;


            }
			$result['code'] = 0;
	        $result['msg'] = "请求成功";
	        $result['data'] = $list_data;
		}else
		{
			$result['code'] = -1;
            if ($params['page'] > 1){
                $result['msg'] = "到底了!";
            }else{
                $result['msg'] = "即将上线!";
            }
		}
		echo json_encode($result);
	}
}